package com.mazaiting.rabbitmq.callback;

import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.common.core.ex.runtime.ValidationException;
import com.mazaiting.rabbitmq.constant.MqConstant;
import com.mazaiting.rabbitmq.domain.entity.MqMessage;
import com.mazaiting.rabbitmq.service.IMqMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 生产端 Return 机制
 *
 * @author mazaiting
 * @create_time 2022/4/1 23:39
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ReturnsCallback implements RabbitTemplate.ReturnsCallback {

    private final IMqMessageService mqMessageService;

    /**
     * 处理不可路由的消息
     *
     * @param returned 消息
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        // 进入此方法的消息都是发送失败的消息
        // spring_returned_message_correlation 消息的 UUID
        log.error("returnedMessage: " + returned);
        log.error("消息 ID: " + returned.getMessage().getMessageProperties().getHeader(MqConstant.KEY_RETURNED_MESSAGE_CORRELATION).toString());
        // 消息 ID
        String messageId = returned.getMessage().getMessageProperties().getMessageId();
        log.error("消息 ID: " + messageId);
        // 根据 ID 获取消息
        MqMessage mqMessage = mqMessageService.getById(messageId);
        if (Objects.isNull(mqMessage)) {
            throw new ValidationException(ResultCode.MQ_MESSAGE_EMPTY);
        }
        mqMessage.setSendStatus(false);
        mqMessage.setErrorMsg(returned.getReplyText());
        mqMessageService.updateById(mqMessage);
    }
}
